package com.howen.framework;
import com.microsoft.playwright.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BrowserEngine {
    private Playwright playwright;
    private Browser browser;
    private String baseUrl;

    /**
     * 初始化配置数据
     * @throws IOException
     */
    public void initConfigData() throws IOException {
        Properties p = new Properties();
        try (InputStream ips = getClass().getClassLoader().getResourceAsStream("config.properties")){
            if (ips == null){
                throw new IOException("config.properties 找不到啊，请确认文件目录是不是正确放在目录下");
            }
            p.load(ips);
            baseUrl = p.getProperty("URL");
            if(baseUrl == null || baseUrl.isEmpty()){
                throw new IOException("config.properties 没找到啊,配置文件中缺少了URL的配置");
            }
            baseUrl = baseUrl.replaceAll("/+$","");
        }
    }

    /**
     * 获取浏览器
     * @return
     */
    public Page getBrowser() {
        playwright = Playwright.create();
        BrowserType.LaunchOptions options = new BrowserType.LaunchOptions()
                .setHeadless(false)
                .setSlowMo(50);

        browser = playwright.chromium().launch(options);
        BrowserContext context = browser.newContext(new Browser.NewContextOptions()
                .setViewportSize(1920, 1080));

        return context.newPage();
    }

    /**
     * 获取baseUrl
     * @return
     */
    public String getBaseUrl() {
        return baseUrl;
    }

    /**
     * 关闭浏览器
     */
    public void close() {
        if (browser != null) browser.close();
        if (playwright != null) playwright.close();
    }

}
